# _*_ coding:utf-8 _*_
# @Time  : 2022.10.12
# @Author: zizlee
import datetime
import json
import time
import pandas as pd

import requests
from urllib3 import disable_warnings
from iFinDPy import THS_iFinDLogin, THS_iFinDLogout, THS_HQ

disable_warnings()

HOST = 'https://210.13.218.130:9000/'


# def get_date_rng(start, end):  # 获取起始日期到结束日期的每月的最后一天
#     start_date = datetime.datetime.strptime(start, '%Y%m%d').date()
#     end_date = datetime.datetime.strptime(end, '%Y%m%d').date()
#     return [m.strftime('%Y%m%d') for m in pd.date_range(start_date, end_date, freq='M')]


def print_progress_bar(current, total, color=35, title=''):  # percent是小数
    percent = round(current/total, 4)
    prefix_progress = '▓' * int(80 * percent)
    leave_progress = '▓' * (80 - int(80 * percent))
    # percent = '%.2f' % (percent * 100)
    print(f'\033[1;{color}m{current}/{total}\033[0m|\033[1;{color}m{prefix_progress}\033[0m{leave_progress} {title}')


def read_indexes(pointers=None):
    with open('R_主力年度涨跌幅.json', encoding='utf8', mode='r') as fp:
        indexes = json.load(fp)
    if pointers:
        indexes = list(filter(lambda x: x['source_id'] in pointers, indexes))
    print('读取本地数量:', len(indexes))

    # 读取网络指标数据，过滤并修改起始日期
    r = requests.get(HOST + 'v1/datalib/table/indexGroups/', verify=False)
    customer_indexes = None
    for g in r.json()['data']:
        if g['group'] == 'rj1':
            customer_indexes = list(filter(lambda x: 6340 <= x['id'] <= 6500, g['data']))
    # print('读取网络指标数量:', len(customer_indexes))

    local_indexes = {i['source_id']: i['ths_code'] for i in indexes}
    price_types = {i['source_id']: i['price_type'] for i in indexes}
    customer_indexes = list(filter(lambda x: x['source_id'] in local_indexes.keys(), customer_indexes))
    for ci in customer_indexes:
        ci['ths_code'] = local_indexes.get(ci['source_id'])
        ci['price_type'] = price_types.get(ci['source_id'])
        if not ci['ths_code'] or not ci['price_type']:
            raise ValueError(f'{ci["name_zh"]}指标不存在！')
    print('待更新指标数量:', len(customer_indexes))

    return customer_indexes


def get_index_values(index_item):
    start_date = index_item['enddate'] if index_item['enddate'] else index_item['startdate']
    ths_code = index_item['ths_code']
    if index_item['price_type'] == 'close':
        # 历史行情-期货-前收盘价,收盘价-年
        # 获取收盘价时年度得再减一年计算才会正确,初次更新不需要
        close_start_date = '%s-12-01' % (int(start_date[:4]) - 1) if index_item['enddate'] else start_date
        ret = THS_HQ(ths_code, 'open,close', 'Interval:Y', close_start_date, CLOSE_DATE)
        if ret.errorcode != 0:
            print(f'\033[1;34m获取 {index_item["source_id"]} 数据, 起始日期:{start_date}.失败了，code={ret.errorcode}:{ret.errmsg} \033[0m')
            return []
        df = ret.data
        # 计算年度涨跌
        df['preClose'] = df['close'].shift(1)
        # 第一行的preClose=open
        df.loc[0, 'preClose'] = df.loc[0, 'open']
        # 计算涨跌幅
        df['datavalue'] = ((df['close'] - df['preClose']) * 100 / df['preClose']).round(2)
        df.rename(columns={'time': 'datadate'}, inplace=True)
        df = df[df['datadate'] >= start_date]
        return df[['datadate', 'datavalue']].to_dict(orient='records')
    elif index_item['price_type'] == 'settlement':
        ret = THS_HQ(ths_code, 'preSettlement,settlement', 'Interval:Y', start_date, CLOSE_DATE)
        if ret.errorcode != 0:
            print(f'\033[1;34m获取 {index_item["source_id"]} 数据, 起始日期:{start_date}.失败了，code={ret.errorcode}:{ret.errmsg} \033[0m')
            return []
        df = ret.data
        df['datavalue'] = ((df['settlement'] - df['preSettlement']) * 100 / df['preSettlement']).round(2)
        df.rename(columns={'time': 'datadate'}, inplace=True)
        return df[['datadate', 'datavalue']].to_dict(orient='records')
    else:
        return []


def save_index(sheet_id, datalist):
    url = HOST + 'v1/datalib/table/update/'
    body_data = {'dataid': sheet_id, 'row_value': datalist}
    r = requests.post(url, json=body_data, verify=False)
    return r.json()['code'] == 200


if __name__ == '__main__':
    CLOSE_DATE = '2022-12-31'
    index_list = read_indexes()
    total_count = len(index_list)

    with open('../ths.config.json', 'r') as ths:
        ths_configs = json.load(ths)

    login_rep = THS_iFinDLogin(ths_configs['USER'], ths_configs['PSWD'])
    if login_rep != 0:
        raise AssertionError(f'登录THS失败:{login_rep}！')

    for c_index, item in enumerate(index_list):
        values = get_index_values(item)
        if not len(values):
            continue
        success = save_index(item['id'], values)
        if success:
            message = f'{item["name_zh"]},指标{item["source_id"]},起始日期:{values[0]["datadate"]}保存完成.'
            color = 35
        else:
            message = f'{item["name_zh"]},指标{item["source_id"]},起始日期:{values[0]["datadate"]}保存失败!'
            color = 31
        print_progress_bar(current=c_index + 1, color=color, total=total_count, title=message)
        time.sleep(1)
    THS_iFinDLogout()
